<template> 
  <div class="register-container">
    <img src="../../assets/images/registerbackground.jpg" alt="background" class="background-image">
    <!-- 快帮帮logo -->
    <div class="register-logo">
      <img src="../../assets/images/Logo.png" alt="logo" class="logo-image">
      <span class="system-name">快帮帮</span>
    </div>
    <!-- 注册主体 -->
    <div class="register-body">
      <h3>注册</h3>
      <div class="info">
        <van-cell-group inset>
          <!-- 用户名输入框 -->
          <van-field 
            v-model="formData.username" 
            label="用户名" 
            label-class="lc"
            label-align="top" 
            class="custom-field"
            :error-message="errors.usernameErrorMsg"
            > 
            <template #input>
              <input 
                v-model="formData.username" 
                placeholder="请输入用户名（最多20字符）" 
                class="input-field" 
                @input="validateUsername" 
                @blur="validateUsername" />
            </template>
            
          </van-field>
          <!-- 密码输入框 -->
          <van-field 
            v-model="formData.password" 
            label="密码" 
            type="password" 
            label-align="top" 
            class="custom-field"
            :error-message="errors.passwordErrorMsg">
            <template #input>
              <input 
                v-model="formData.password" 
                placeholder="请输入密码（最多20字符）" 
                class="input-field" 
                @input="validatePassword" 
                @blur="validatePassword" />
            </template>
          </van-field>
          <!-- 邮箱输入框 -->
          <van-field 
            v-model="formData.email" 
            label="邮箱" 
            label-align="top" 
            class="custom-field"
            :error-message="errors.emailErrorMsg">
            <template #input>
              <input 
                v-model="formData.email" 
                placeholder="请输入正确邮箱" 
                class="input-field" 
                @input="validateEmail" 
                @blur="validateEmail" />
            </template>
          </van-field>
          <!-- 验证码输入框 -->
          <van-field 
            v-model="formData.otp" 
            label="验证码" 
            label-align="top" 
            class="custom-field"
            :error-message="errors.otpErrorMsg">
            <template #input>
              <input 
                v-model="formData.otp" 
                placeholder="请输入验证码" 
                class="input-field"
                @input="validateOtp" 
                @blur="validateOtp" />
            </template>
            <template #button>
              <van-button size="small" @click="sendotp">发送验证码</van-button>
            </template>
          </van-field>
        </van-cell-group>
      </div>

      <!-- 注册按钮 -->
      <div class="btn" @click="onRegister">
        <van-button color="#4095E5" type="primary" size="large" block class="custom-button">注册</van-button>
      </div>

      <!-- 转向登录界面 -->
      <div class="other">
        <div class="login">
          <span>已有账号？</span>
          <a href="/login" class="login-link">立即登录</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { register, sendCode } from "../../api/Register";

const router = useRouter();
//请求数据
const formData = reactive({
  username: "",
  password: "",
  email: "",
  otp: "",
});

// 错误信息
const errors = reactive({
  usernameHasError: false, // 用于表示用户名是否有错误状态
  usernameErrorMsg: "", // 用于存储具体的错误提示信息
  passwordHasError: false,
  passwordErrorMsg: "",
  emailHasError: false,
  emailErrorMsg: "",
  otpHasError: false,
  otpErrorMsg: "",
});

// 验证用户名
const validateUsername = () => {
  // 先检查长度
  if (formData.username.length > 20) {
    errors.usernameHasError = true;
    errors.usernameErrorMsg = "用户名不能超过20个字符";
    return false;
  }
  // 再检查内容
  const usernameRegex = /^[a-zA-Z0-9]+$/; // 只允许字母和数字
  if (!usernameRegex.test(formData.username)) {
    errors.usernameHasError = true;
    errors.usernameErrorMsg = "用户名仅限字母和数字";
    return false;
  }
  errors.usernameHasError = false;
  errors.usernameErrorMsg = "";
  return true;
};

// 验证密码
const validatePassword = () => {
  // 先检查长度
  if (formData.password.length > 20) {
    errors.passwordErrorMsg = "密码不能超过20个字符";
    errors.passwordHasError = true;
    return false;
  }
  // 再检查内容
  const passwordRegex = /^[a-zA-Z0-9]+$/;
  if (!passwordRegex.test(formData.password)) {
    errors.passwordErrorMsg = "密码仅限字母和数字";
    errors.passwordHasError = true;
    return false;
  }
  errors.passwordErrorMsg = "";
  errors.passwordHasError = false;
  return true;
};

// 验证邮箱
const validateEmail = () => {
  const emailRegex = /^[\w-]+@([\w-]+\.)+[\w-]{2,4}$/;
  if (!emailRegex.test(formData.email)) {
    errors.emailErrorMsg = "邮箱格式不正确";
    errors.emailHasError = true;
    return false;
  }
  errors.emailErrorMsg = "";
  errors.emailHasError = false;
  return true;
};

// 验证验证码
const validateOtp = () => {
  if (!formData.otp) {
    errors.otpErrorMsg = "验证码不能为空";
    return false;
  }
  errors.otpErrorMsg = "";
  return true;
};

// 验证表单
const validateForm = () => {
  return (
    validateUsername() &&
    validatePassword() &&
    validateEmail() &&
   !!formData.otp
  );
};

// 发送验证码
const sendotp = async () => {
  if (validateEmail()) {
    try {
      await sendCode(formData.email);
      alert("验证码已发送至您的邮箱");
    } catch (error) {
      alert("验证码发送失败");
    }
  }
};

// 发送注册请求
const onRegister = async () => {
  if (validateForm()) {
    try {
      const response=await register(formData);
      if(response.data.code===400){
        errors.usernameErrorMsg = "用户名已存在";
        return;
      }else if(response.data.code===401){
        errors.otpErrorMsg = "验证码错误";
        return;
      }else if(response.data.code===200){
        alert("注册成功");
      }else if(response.data.code===403){
        alert("请先获取验证码");
      }
      console.log(response.data);
      router.replace("/login");
    } catch (error) {
      alert("注册失败，请检查输入信息");
    }
  } else {
    alert("请修正错误信息后再提交");
  }
};
</script>

<style lang="less" scoped>
.register-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  z-index: -1;
}

.register-logo {
  position: absolute;
  top: 113px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1;
}

.logo-image {
  width: 118px;
  height: 111px;
}

.system-name {
  text-align: center;
  color: #FFFFFF;
  font-size: 20px;
}

.register-body {
  position: absolute;
  width: 317px;
  height: 500px;
  top: 240px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #FFFFFF;
  border-radius: 13px;
  margin-top: 20px;
}

.register-body h3 {
  text-align: center;
  margin-top: 22px;
}

.custom-field{
  height: 90px;
  display: grid;
  grid-template-rows: auto auto;
  padding-top: 1px;
  position: relative;
}

.custom-field .van-field__label {
  margin-bottom: 0px; /* 调整标签和输入框之间的间距 */
}

.custom-field .van-field__body {
  position: relative;
}

.input-field {
  width: 100%;
  height: 36px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px;
  box-sizing: border-box;
  color: black;
}

/* 错误提示样式 */
.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px; 
  display: block;  
}

.has-error {
  border-color: red;
}

.btn {
  width: 253px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 300px;
  margin-top: 100px;
}

.info{
  padding-top: 15px;
}

.custom-button {
  height: 36px;
  line-height: 36px;
  position: absolute;
  margin-top: 20px; 
  font-size: 12px;
}

.other {
  font-size: 10px;
  position: absolute;
  top: 360px;
  left: 36px;
  margin-top: 100px;
}

.login-link {
  color: #4095E5;
  font-size: 10px;
}

::v-deep .van-cell__value {
  height: 66px;
}

</style>